<template>
  <view class="maintenance-container">
    <view class="example">
      <uni-forms
        ref="form"
        :model="repairList"
        labelWidth="80px"
      >
        <!--    <uni-forms-item label="设备编码" name="equipmentNo">
          <uni-easyinput v-model="repairList.equipmentNo" disabled="true" />
          <button v-if="maintenanceCode==''" type="primary" size="mini" class="btnChooseAddress"
            @tap="clickEqumetEdit">选择维修设备</button>
        </uni-forms-item> -->
        <uni-forms-item
          label="设备分类"
          name="equipmentClassification"
        >
          <uni-easyinput
            v-model="repairList.equipmentClassification"
            :disabled="maintenanceStatus == 0 ? false : true"
            placeholder="请输入设备分类"
          />
          <!-- <uni-data-select v-model="repairList.equipmentClassification" :disabled="maintenanceStatus == 0?false:true"
            :localdata="eqClassification" /> -->
        </uni-forms-item>
        <uni-forms-item
          label="报修地址"
          name="warrantyAddress"
        >
          <uni-easyinput
            v-model="repairList.warrantyAddress"
            :disabled="maintenanceStatus == 0 ? false : true"
          />
          <button
            v-if="maintenanceStatus == 0"
            type="primary"
            size="mini"
            class="btnChooseAddress"
            @tap="chooseAddress"
          >
            {{
              repairList.warrantyAddress == '' ? '选择报修地址' : '修改报修地址'
            }}
          </button>
        </uni-forms-item>
        <uni-forms-item label="报修人">
          <uni-easyinput
            v-model="userName"
            disabled="true"
          />
        </uni-forms-item>
        <uni-forms-item
          label="客户号码"
          name="customerNumber"
        >
          <uni-easyinput
            v-model="repairList.customerNumber"
            :disabled="maintenanceStatus == 0 ? false : true"
          />
        </uni-forms-item>
        <uni-forms-item
          label="紧急程度"
          name="urgency"
        >
          <uni-data-select
            v-model="repairList.urgency"
            v-if="maintenanceStatus == 0 || maintenanceStatus == null"
            :localdata="range"
          />
          <uni-easyinput
            :value="repairList.urgency == 0 ? '普通维修' : '紧急维修'"
            v-if="maintenanceStatus == 1"
            disabled="true"
          />
        </uni-forms-item>
        <uni-forms-item
          label="报修描述"
          name="taskDescription"
        >
          <uni-easyinput
            type="textarea"
            v-model="repairList.taskDescription"
            placeholder="请说明要维修的情况、出现状况，如何导致等.."
            :disabled="maintenanceStatus == 0 ? false : true"
            :maxlength="max"
          />
        </uni-forms-item>
        <uni-forms-item
          label="文件上传"
          name="imgupload"
        >
          <view class="right">
            <view
              class="feedback-image-item"
              v-for="(item, index) in maintenanceImgList"
              :key="index"
            >
              <view
                v-if="maintenanceStatus == 0"
                class="close-icon"
                @tap="deleteFile(index, item.id, 'img')"
              >
                <uni-icons
                  type="closeempty"
                  size="18"
                  color="#fff"
                ></uni-icons>
              </view>
              <view class="image-box">
                <image
                  :src="item.url"
                  mode="aspectFill"
                  @tap="previewImg(index, item.url)"
                ></image>
              </view>
            </view>
            <!-- 视频 -->
            <view
              class="feedback-image-item"
              v-for="(item, index) in videoList"
              :key="index"
            >
              <view
                v-if="maintenanceStatus == 0"
                class="close-icon"
                @tap="deleteFile(index, item.id, 'video')"
              >
                <uni-icons
                  type="closeempty"
                  size="18"
                  color="#fff"
                ></uni-icons>
              </view>
              <view class="image-box">
                <video
                  :src="item.url"
                  class="video"
                ></video>
              </view>
            </view>
            <view
              v-if="maintenanceImgList.length < 5 && maintenanceStatus == 0"
              class="feedback-image-item"
              @tap="addImage"
            >
              <view class="image-box">
                <uni-icons
                  type="plusempty"
                  size="50"
                  color="#c7c7c7"
                ></uni-icons>
              </view>
            </view>
          </view>
        </uni-forms-item>
      </uni-forms>
      <button
        v-if="maintenanceStatus == 0"
        type="primary"
        @tap="submit"
      >
        提交
      </button>
    </view>
    <view>
      <!-- 输入框示例 -->
      <uni-popup
        ref="popup"
        background-color="#fff"
        :show="show"
      >
        <view class="popup-content">
          <uni-table
            ref="table"
            :loading="loading"
            border
            stripe
            emptyText="暂无更多数据"
            @selection-change="selectionChange"
          >
            <uni-tr>
              <uni-th
                width="80"
                align="center"
                >设备编号</uni-th
              >
              <uni-th align="center">设备名称</uni-th>
              <uni-th
                width="100"
                align="center"
                >操作</uni-th
              >
            </uni-tr>
            <uni-tr
              v-for="(item, index) in equimentList"
              :key="index"
            >
              <uni-td align="center">
                <view class="name">{{ item.equipmentNo }}</view>
              </uni-td>
              <uni-td align="center">{{ item.equipmentName }}</uni-td>
              <uni-td align="center">
                <view class="uni-group">
                  <button
                    class="uni-button"
                    size="mini"
                    type="primary"
                    @tap="clickEqumetItem(item)"
                  >
                    选择
                  </button>
                </view>
              </uni-td>
            </uni-tr>
          </uni-table>
          <view class="uni-pagination-box"
            ><uni-pagination
              show-icon
              :page-size="equimentqueryParams.pageSize"
              :current="equimentqueryParams.pageNum"
              :total="equimentTotal"
              @change="change"
            />
          </view>
        </view>
        <view class="btn_item">
          <button
            class="cancal"
            type="warn"
            @tap="close"
            size="mini"
          >
            关闭
          </button>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script>
  import {
    getTask,
    addTask,
    updateTask,
    uploadMaintenanceImgAdd,
    uploadMaintenanceVideoAdd,
    querymaintenceImgList,
    querymaintenceVideoList,
    delImgbyId,
    selectAllMaintenanId,
    sendMessage,
  } from '@/api/system/task/task.js'
  import config from '@/config'
  import user from '../../store/modules/user.js'
  import getDateTime from '../../utils/getdateTime.js'
  import { listEquipmentNotTask } from '@/api/system/equiment/equipment.js'
  import { getUserItme } from '@/api/system/user'
  import { fail } from 'assert'
  export default {
    data() {
      return {
        path: '',
        baseUrl: config.baseUrl,
        //是否有弹框
        show: false,
        repairList: {
          equipmentNo: null,
          warrantyPersonId: '',
          maintainerId: '',
          warrantyAddress: '',
          urgency: '',
          warrantyDate: '',
          taskDescription: '',
          taskDescription: '',
          equipmentClassification: '',
          customerNumber: '',
        },
        loading: false,
        max: 500,
        // 数据总量
        equimentTotal: 0,
        equimentList: [],
        maintenanceImgList: [],
        maintenanceImgEditList: [],
        maintenanceStateList: [],
        imglist: [],
        queryImgList: {
          pageNum: 1,
          pageSize: 5,
          maintenanceImgCode: '',
        },
        equimentqueryParams: {
          pageNum: 1,
          pageSize: 5,
          customerId: '',
        },
        maintenanceCode: '',
        maintenanceStatus: '',
        rules: {
          // equipmentNo: {
          //   rules: [{
          //       required: true,
          //       errorMessage: '设备编码不能为空'
          //     },
          //     {
          //       format: 'number',
          //       errorMessage: '设备编码只能为数字'
          //     }
          //   ]
          // },
          customerNumber: {
            rules: [
              {
                required: true,
                errorMessage: '客户号码不能为空',
              },
              {
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                errorMessage: '请输入正确的手机号码',
              },
            ],
          },
          warrantyAddress: {
            rules: [
              {
                required: true,
                errorMessage: '报修地址不能为空',
              },
            ],
          },
          urgency: {
            rules: [
              {
                required: true,
                errorMessage: '紧急程度不能为空',
              },
            ],
          },
          taskDescription: {
            rules: [
              {
                required: true,
                errorMessage: '设备描述不能为空',
              },
            ],
          },
          equipmentClassification: {
            rules: [
              {
                required: true,
                errorMessage: '设备分类不能为空',
              },
            ],
          },
        },
        range: [],
        eqClassification: [],
        userName: this.$store.state.user.name,
        userId: null,
        phonenumber: null,
        nickname: null,
        openid: null,
        flag: false,
        videoList: [], //视频存放
        videoEditList: [],
        sourceTypeIndex: 2,
        checkedValue: true,
        checkedIndex: 0,
        sourceType: ['拍摄', '相册', '拍摄或相册'],
        cameraList: [
          {
            value: 'back',
            name: '后置摄像头',
            checked: 'true',
          },
          {
            value: 'front',
            name: '前置摄像头',
          },
        ],
        cameraIndex: 0,
      }
    },
    created() {
      //显示紧急程度下拉列表
      this.getDicts('task_urgency').then((response) => {
        this.range = response.data.map((x) => ({
          value: parseInt(x.dictValue),
          text: x.dictLabel,
        }))
      })
      this.getDicts('equipment_classification').then((response) => {
        this.eqClassification = response.data.map((x) => ({
          value: parseInt(x.dictValue),
          text: x.dictLabel,
        }))
      })
    },
    onLoad(option) {
      if (option.userid != null) {
        this.userId = option.userid
        this.phonenumber = option.phonenumber
        this.nickname = option.nickname
      }
      //判断是否有id查询数据到表单
      if (option.maintenanceCode != null && option.maintenanceStatus != null) {
        this.maintenanceCode = option.maintenanceCode
        this.maintenanceStatus = option.maintenanceStatus
        this.getwarrantyItem()
      }
      //扫码跳转过来有设备id直接赋值
      if (option.equipmentNo != null) {
        this.repairList.equipmentNo = option.equipmentNo
      }
    },
    //清空
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    onUnload() {
      ;(this.src = ''),
        (this.sourceTypeIndex = 2),
        (this.sourceType = ['拍摄', '相册', '拍摄或相册'])
    },
    methods: {
      //查询没有绑定的设备方法
      getlistEquipmentNotTask() {
        this.loading = true
        listEquipmentNotTask(this.equimentqueryParams).then((response) => {
          if (response.code === 200) {
            this.equimentList = response.rows
            this.equimentTotal = response.total
            this.loading = false
          }
        })
      },
      //修改时候，将存在的图片查询显示
      getwarrantyItem() {
        getTask(this.maintenanceCode).then((response) => {
          if (response.code === 200) {
            this.repairList = response.data
            this.queryImgList.maintenanceImgCode = response.data.maintenanceCode
            this.queryimgAndvideoList('img')
            this.queryimgAndvideoList('video')
          }
        })
      },
      //查询
      queryimgAndvideoList(type) {
        if (type == 'img') {
          querymaintenceImgList(this.queryImgList).then((response) => {
            if (response.code === 200) {
              response.rows.forEach((item, index) => {
                this.maintenanceImgList.push({
                  url: this.baseUrl + item.maintenanceImgUrl,
                  id: item.id,
                })
              })
            }
          })
        } else {
          querymaintenceVideoList(this.queryImgList).then((response) => {
            if (response.code === 200) {
              response.rows.forEach((item, index) => {
                this.videoList.push({
                  url: this.baseUrl + item.maintenanceImgUrl,
                  id: item.id,
                })
              })
            }
          })
        }
      },
      //删除图片
      deleteFile(index, id, type) {
        if (type == 'img') {
          this.$modal.confirm('确定删除此图片吗？').then(() => {
            this.maintenanceImgList.splice(index, 1)
            if (this.maintenanceCode !== '' && id != null) {
              delImgbyId(id).then((response) => {
                if (response.code == 200) {
                  this.$modal.msgSuccess('删除成功')
                }
              })
            }
          })
        } else {
          this.$modal.confirm('确定删除此视频吗？').then(() => {
            this.videoList.splice(index, 1)
            if (this.maintenanceCode !== '' && id != null) {
              delImgbyId(id).then((response) => {
                if (response.code == 200) {
                  this.$modal.msgSuccess('删除成功')
                }
              })
            }
          })
        }
      },
      //浏览图片
      previewImg(index, url) {
        const thant = this
        //每次点击浏览先清空数组
        thant.imglist = []
        //循环把路径丢到图片列表里面
        thant.maintenanceImgList.forEach((item, index) => {
          thant.imglist.push(item.url)
        })
        uni.previewImage({
          urls: thant.imglist,
          current: url,
          // 下面我这边做的都是默认的选择
          longPressActions: {
            itemList: ['发送给朋友', '保存图片', '收藏'],
            success: function (data) {
              thant.$modal.msgSuccess(data)
            },
            fail: function (err) {
              thant.$modal.msg(data)
            },
          },
        })
      },
      //新增图片
      addImage() {
        uni.showActionSheet({
          title: '选择上传类型',
          itemList: ['图片', '视频'],
          success: (res) => {
            if (res.tapIndex == 0) {
              this.chooseImages()
            } else {
              this.chooseVideo()
            }
          },
        })
      },
      //上传图片
      chooseImages() {
        const count = 5 - this.maintenanceImgList.length
        uni.chooseImage({
          count: count, // 最多可以选择的图片张数，默认9
          sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
          sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
          success: (res) => {
            const tempFilePaths = res.tempFilePaths
            tempFilePaths.forEach((item, index) => {
              if (index < count) {
                //处理小程序多选状况
                this.maintenanceImgList.push({
                  url: item,
                })
              }
            })
          },
        })
      },
      // 上传视频
      chooseVideo() {
        const thant = this
        uni.chooseVideo({
          maxDuration: 20,
          camera: thant.cameraList[thant.cameraIndex].value,
          sourceType: thant.sourceType[thant.sourceTypeIndex],
          success: (res) => {
            thant.videoList.push({ url: res.tempFilePath })
          },
          fail: (err) => {
            thant.$modal.msgError(err)
          },
        })
      },
      //这里触发图片上传的方法
      uploadimg(index, maintenanceCode) {
        //判断是修改还是新增
        if (this.maintenanceCode !== '') {
          this.path = this.maintenanceImgEditList[index].url
        } else {
          this.path = this.maintenanceImgList[index].url
        }
        //设备id，图片名称，路径
        let data = {
          equipmentCode: maintenanceCode,
          name: 'maintenanceImg',
          filePath: this.path,
        }
        //保存到数据库的方法调用
        uploadMaintenanceImgAdd(data).then((response) => {
          if (response.code == 200) {
            if (this.maintenanceCode !== '') {
              uni.showToast({
                title: '修改成功',
                icon: 'success',
              })
            } else {
              uni.showToast({
                title: '新增成功',
                icon: 'success',
              })
            }
          }
        })
      },
      //这里触发图片上传的方法
      uploadVideo(index, maintenanceCode) {
        //判断是修改还是新增
        if (this.maintenanceCode !== '') {
          this.path = this.videoEditList[index].url
        } else {
          this.path = this.videoList[index].url
        }
        //设备id，图片名称，路径
        let data = {
          equipmentCode: maintenanceCode,
          name: 'maintenanceVideo',
          filePath: this.path,
        }
        //保存到数据库的方法调用
        uploadMaintenanceVideoAdd(data).then((response) => {
          if (response.code == 200) {
            if (this.maintenanceCode !== '') {
              uni.showToast({
                title: '修改成功',
                icon: 'success',
              })
            } else {
              uni.showToast({
                title: '新增成功',
                icon: 'success',
              })
            }
          }
        })
      },
      //提交
      submit(ref) {
        this.$refs.form.validate().then((res) => {
          this.repairList.warrantyDate = getDateTime.dateTimeStr('y-m-d h:i:s')
          if (this.maintenanceCode !== '') {
            //更新报修单
            updateTask(this.repairList).then((response) => {
              if (response.code === 200) {
                //判断修改是有没有新增图片
                if (this.maintenanceImgList.length > 0) {
                  //再循环把新增的图片加进来，已经存在的过滤
                  this.maintenanceImgList.forEach((item, index) => {
                    const indexUrl = item.url.substring(7, 10)
                    const wxUrl = item.url.substring(0, 6)
                    if (wxUrl == 'wxfile' || indexUrl == 'tmp') {
                      this.maintenanceImgEditList.push({
                        url: item.url,
                      })
                    }
                  })
                  //新增的图片上传，没有新增的不上传
                  if (this.maintenanceImgEditList.length > 0) {
                    this.maintenanceImgEditList.forEach((item, index) => {
                      this.uploadimg(index, this.maintenanceCode)
                    })
                  }
                }
                if (this.videoList.length > 0) {
                  //再循环把新增的图片加进来，已经存在的过滤
                  this.videoList.forEach((item, index) => {
                    const indexUrl = item.url.substring(7, 10)
                    const wxUrl = item.url.substring(0, 6)
                    if (wxUrl == 'wxfile' || indexUrl == 'tmp') {
                      this.videoEditList.push({
                        url: item.url,
                      })
                    }
                  })
                  //新增的图片上传，没有新增的不上传
                  if (this.videoEditList.length > 0) {
                    this.videoEditList.forEach((item, index) => {
                      this.uploadVideo(index, this.maintenanceCode)
                    })
                  }
                }
                uni.$emit('toItem')
                uni.navigateBack({
                  delta: 1,
                  success: (res) => {
                    if ((res.errMsg = 'navigateBack:ok')) {
                      if (
                        this.maintenanceImgEditList.length <= 0 ||
                        this.videoEditList.length <= 0
                      ) {
                        uni.showToast({
                          title: '修改成功',
                          icon: 'success',
                        })
                      }
                    }
                  },
                })
              }
            })
          } else {
            //新增报修单
            this.repairList.warrantyPersonId = this.userId
            addTask(this.repairList).then((response) => {
              if (response.code === 200) {
                //判断是否有新增的图片，循环上传
                if (this.maintenanceImgList.length > 0) {
                  this.maintenanceImgList.forEach((item, index) => {
                    this.uploadimg(index, response.data)
                  })
                }
                if (this.videoList.length > 0) {
                  this.videoList.forEach((item, index) => {
                    this.uploadVideo(index, response.data)
                  })
                }
                uni.reLaunch({
                  url: '/subpkg/index/index',
                  success: (res) => {
                    if ((res.errMsg = 'reLaunch:ok')) {
                      uni.showToast({
                        title: '新增成功',
                        icon: 'success',
                      })
                    }
                  },
                })
              }
            })

            //查询维修人员单最少或者没有单的进行获取
            // selectAllMaintenanId({
            //   userId: null
            // }).then(response => {
            //   if (response.code === 200 && response.rows[0] != null) {
            //     this.repairList.maintainerId = response.rows[0].user.userId
            //     this.repairList.warrantyPersonId = this.userId
            //     getUserItme(this.repairList.maintainerId).then(response => {
            //       if (response.code == 200) {
            //         this.openid = response.data.openId
            //         addTask(this.repairList).then(response => {
            //           if (response.code === 200) {
            //              this.flag = false
            //             //判断是否有新增的图片，循环上传
            //             if (this.maintenanceImgList.length > 0) {
            //                 this.maintenanceImgList.forEach((item, index) => {
            //                 this.uploadimg(index, response.data)
            //               })
            //             }
            //             uni.reLaunch({
            //               url: "/subpkg/index/index",
            //               success: (res) => {
            //                 if (res.errMsg = "reLaunch:ok") {
            //                   if (this.openid != null) {
            //                     //新增成功调用接口
            //                     const data = {
            //                       openid: this.openid,
            //                       selfPage: '/pages/login',
            //                       maintenanceCode: response.data,
            //                       urgency: this.repairList.urgency == 0 ? '普通维修' : '紧急维修',
            //                       username: this.nickname,
            //                       phonenumber: this.phonenumber,
            //                       description:  this.repairList.urgency == 0 ? '您有一份普通维修单,请在7天内及时处理' : '您有一份紧急维修单,请在3天内及时处理'
            //                     }
            //                     sendMessage(data).then(response => {
            //                       if (response.errcode == 0) {
            //                         uni.showToast({
            //                           title: "新增成功",
            //                           icon: 'success'
            //                         })
            //                       } else {
            //                         uni.showToast({
            //                           title: "订阅失败",
            //                           icon: 'error'
            //                         })
            //                       }
            //                     })
            //                   } else {
            //                     uni.showToast({
            //                       title: "新增成功",
            //                       icon: 'success'
            //                     })
            //                   }
            //                 }
            //               }
            //             })
            //           }
            //         })
            //       }
            //     })
            //   }else{
            //     uni.showModal({
            //       title: '提示',
            //       content: '暂无其他维修员可派发，请联系管理员',
            //       showCancel: false,
            //     });
            //   }
            // })
          }
        })
      },
      // 选择报修地址
      async chooseAddress() {
        //弹窗定位让其选择，成功后把地址和名称一起赋值给地址字段
        uni.chooseLocation({
          success: (res) => {
            this.repairList.warrantyAddress = res.address + res.name
          },
          fail: (err) => {
            this.$modal.errorMessage(err)
          },
        })
      },
      //选择设备
      clickEqumetEdit() {
        //根据当前用户id查询该用户下没有绑定的设备
        this.equimentqueryParams.customerId = this.userId
        this.getlistEquipmentNotTask()
        this.$refs.popup.open()
      },
      //选择派发人员取消
      close() {
        // TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
        this.$refs.popup.close()
      },
      // 分页触发
      change(e) {
        this.equmentqueryParams.pageNum = e.current
        this.getlistEquipmentNotTask()
      },
      //选择某一台设备
      clickEqumetItem(item) {
        this.repairList.equipmentNo = item.equipmentNo
        this.$refs.popup.close()
      },
    },
  }
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }

  .example {
    padding: 15px;
    background-color: #fff;
  }

  .segmented-control {
    margin-bottom: 15px;
  }

  .button-group {
    margin-top: 15px;
    display: flex;
    justify-content: space-around;
  }

  .form-item {
    display: flex;
    align-items: center;
    flex: 1;
  }

  .button {
    display: flex;
    align-items: center;
    height: 35px;
    line-height: 35px;
    margin-left: 10px;
  }

  .btnChooseAddress {
    margin-top: 5px;
  }

  .example {
    padding: 15px;
    background-color: #fff;
  }

  .segmented-control {
    margin-bottom: 15px;
  }

  .button-group {
    margin-top: 15px;
    display: flex;
    justify-content: space-around;
  }

  .form-item {
    display: flex;
    align-items: center;
    flex: 1;
  }

  .button {
    display: flex;
    align-items: center;
    height: 35px;
    line-height: 35px;
    margin-left: 10px;
  }

  .btn_item {
    display: flex;
    margin: 20rpx 0;
  }

  .uni-uploader__file,
  .uploader_video {
    position: relative;
    z-index: 1;
    width: 200rpx;
    height: 200rpx;
  }
  .video {
    width: 100%;
    height: 100%;
  }
  .icon-cuo {
    position: absolute;
    right: 0;
    top: 5upx;
    background: linear-gradient(
      90deg,
      rgba(251, 91, 80, 1) 0%,
      rgba(240, 45, 51, 1) 100%
    );
    color: #ffffff;
    z-index: 999;
    border-top-right-radius: 20upx;
    border-bottom-left-radius: 20upx;
  }

  .right {
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx;

    .feedback-image-item {
      position: relative;
      width: 33.33%;
      height: 0;
      padding-top: 33.33%;
      box-sizing: border-box;

      .close-icon {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 0;
        right: 0;
        width: 44rpx;
        height: 44rpx;
        border-radius: 50%;
        background-color: #ff5a5f;
        z-index: 2;
      }

      .image-box {
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        top: 10rpx;
        right: 10rpx;
        left: 10rpx;
        bottom: 10rpx;
        border: 1px #c7c7c7 solid;
        border-radius: 10rpx;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
</style>
